﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AMS.DD35.Common.Data;
using AMS.DD35.Common;
using AMS.DD35.WebMVP.State;

namespace AMS.DD35.WebMVP.Models
{
    public class CharacterModel : ICharacterModel
    {
        ICharacterService _character;
        IStateManager _state;

        #region Observer
        public event EventHandler SaveSucceeded;
        private void RaiseSaveSucceeded(EventArgs args)
        {
            EventHandler eh = SaveSucceeded;
            if (eh != null)
                eh(this, args);
        }

        public event EventHandler SaveFailed;
        private void RaiseSaveFailed(EventArgs args)
        {
            EventHandler eh = SaveFailed;
            if (eh != null)
                eh(this, args);
        } 
        #endregion

        public CharacterModel(ICharacterService characterService, IStateManager stateManager)
        {
            this._character = characterService;
            this._state = stateManager;
        }

        public void SaveCharacter(CharacterData character)
        {
            try
            {
                _character.SaveCharacter(character, _state.SessionVariable);
                RaiseSaveSucceeded(EventArgs.Empty);
            }
            catch
            {
                RaiseSaveFailed(EventArgs.Empty);
            }
        }

        public CharacterData GetCharacter(long characterId)
        {
            try
            {
                return _character.GetCharacterData(characterId, _state.SessionVariable);
                // TODo: Change this to raise event
            }
            catch
            {
                // TODO: raise failed event
                return null;
            }
        }

        public IEnumerable<CharacterData> GetCharacters()
        {
            return _character.GetCharactersData(_state.SessionVariable);
        }
    }
}